import { ref } from 'vue'
import { defineStore } from 'pinia'
	import { getLoaction } from '@/utils/index.js'
import { GetAddressApi } from '@/service/index.js'
export const useAddressStore = defineStore('addressStore', () => {
  const lonlat = ref({
		longitude: '',
		latitude: '',
		address: ''
	})
	const addressList = ref([])
	const total = ref() // 获取地址列表的总数
	const isDefaultAddress = ref() // 默认地址
	const checkedAddress = ref() // 选中的地址
	const SETLONLAT = (addr) => {
		if(addr) return lonlat.value = addr
		getLoaction().then(res => {
			lonlat.value = {
				latitude: res.latitude,
				longitude: res.longitude,
				address: res.address.street + res.address.streetNum
			}
		}).catch(err => {
			lonlat.value = {
				latitude: 39.916397,
				longitude: 116.410250,
				address: '锡拉胡同111号'
			}
		})
	}
	const SETADDRESS = (page = 1, page_size = 20) => {
		let params = { page, page_size }
		GetAddressApi(params).then(res => {
			addressList.value = res.data
			total.value = res.total
			const isDefault = res.data.some(item => item.is_default == 1 )
			if (isDefault) {
				res.data.forEach(item => {
					if(item.is_default == 1) {
						isDefaultAddress.value = item
					}
				})
			} else {
				isDefaultAddress.value = res.data[0]
			}
		})
	}
	const SETCHECKEDADDRESS = (info) => {
		checkedAddress.value = info
	}
	return {
		lonlat,
		addressList,
		isDefaultAddress,
		checkedAddress,
		SETLONLAT,
		SETADDRESS,
		SETCHECKEDADDRESS
	}
}, {
  // 数据持久化
	persist: {
		storage: {
			getItem: (key) => {
			  return uni.getStorageSync(key)
			},
			setItem: (key, value) => {
			  return uni.setStorageSync(key, value)
			},
		}
	}
})
